package org.wattdepot.cli.command;

import java.util.ArrayList;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * SensorDataDay Class.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 * 
 */
public class SensorDataDay extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Command 2.6 - Prints a table listing all of the sensor data instances for the specified day.
   * 
   * @param args -
   * @return - string of info
   */
  public String doCommand(List<String> args) {
    String source = args.get(0);
    String day = args.get(1);
    XMLGregorianCalendar startTime = null;
    XMLGregorianCalendar endTime = null;
    XMLGregorianCalendar currentInterval = null;
    List<SensorData> sensorData = new ArrayList<SensorData>();
    StringBuffer buff = new StringBuffer(255);
    String data = null;
    try {
      startTime = Tstamp.makeTimestamp(day);
      endTime = Tstamp.incrementDays(startTime, 1);
      currentInterval = startTime;

      while (Tstamp.lessThan(currentInterval, endTime)) {
        sensorData.add(client.getSensorData(source, currentInterval));
        currentInterval = Tstamp.incrementHours(currentInterval, 6);
      }

      if (sensorData.isEmpty()) {
        buff.append("No Data Found");
      }
      else {
        for (SensorData sensorItem : sensorData) {
          buff.append(sensorItem.getTimestamp().toString());
          buff.append("  Tool: ").append(sensorItem.getTool());
          if (sensorItem.isSetProperties()) {
            buff.append("  Properties: ");
            data = sensorItem.getProperties().getProperty().toString();
            buff.append(data.substring(data.indexOf('=') + 1, data.indexOf(','))).append(": ")
                .append(data.substring(data.lastIndexOf('=') + 1, data.length() - 2));
          }
          buff.append(cr);
        }
      }
    }
    catch (MiscClientException mce) {
      return errorClient;
    }
    catch (BadXmlException bxe) {
      return errorXML;
    }
    catch (ResourceNotFoundException rnfe) {
      return error404;
    }
    catch (NotAuthorizedException nae) {
      return error401;
    }
    catch (Exception e) {
      return errorTimeStamp;
    }
    return buff.toString();
  }

}
